<template>
  <layout-body>
    <!-- 筛选 -->
    <search-form-main count="4">
      <template #searchForm>
        <el-form :model="searchForm" ref="searchFormRef">
          <div class="search-form">
            <el-form-item
              class="search-form-item"
              prop="search_key"
              label="筛选方式"
            >
              <div class="flex">
                <el-select v-model="searchForm.search_key" placeholder="请选择">
                  <el-option
                    v-for="item in searchKeyData"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
                <el-input
                  class="ml5"
                  v-model="_searchValue"
                  @change="searchValueChange"
                  placeholder=""
                />
              </div>
            </el-form-item>
            <el-form-item
              class="search-form-item"
              label="订单类型"
              prop="soucre"
            >
              <el-select v-model="searchForm.soucre" placeholder="请选择">
                <el-option
                  v-for="item in orderSourceEnum"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select> </el-form-item
            ><el-form-item
              class="search-form-item"
              label="付款方式"
              prop="pay_type"
            >
              <el-select v-model="searchForm.pay_type" placeholder="请选择">
                <el-option
                  v-for="item in orderPayTypeEnum"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </div>
          <div class="search-form">
            <el-form-item label="下单时间" prop="create_time">
              <shortcuts-time v-model="searchForm.create_time" />
            </el-form-item>
          </div>
        </el-form>
      </template>
      <template #searchBtn>
        <el-button text plain bg @click="resetSearch(searchFormRef)">重置筛选</el-button>
      </template>
    </search-form-main>
  </layout-body>
  <layout-body-tabs
    class="mt20"
    :tabs="statusTabs"
    v-model="orderStatus"
    @change="changeStatus"
  >
    <!-- 列表 -->
    <table class="order-table" v-loading="initLoading">
      <thead>
        <tr>
          <th width="30">
            <input
              class="order-table-check"
              @click="onCheckAll"
              :class="indeterminate ? 'indeterminate' : ''"
              :checked="isCheckAll"
              type="checkbox"
            />
          </th>
          <th>商品信息</th>
          <th width="140">单价/数量</th>
          <th width="180">金额(元)</th>
          <th width="140">买家</th>
          <th width="140">支付信息</th>
          <th width="140">配送方式</th>
          <th width="140">状态</th>
          <th width="140">操作</th>
        </tr>
      </thead>
      <tbody>
        <template v-for="(item, index) in lists" :key="index">
          <tr>
            <td colspan="8"></td>
          </tr>
          <tr class="tr-line header-row">
            <td width="30" class="text-center">
              <input
                class="order-table-check"
                @change="selectedCheckbox(item.id)"
                :checked="$utils.inArray(item.id, selectedIds)"
                type="checkbox"
              />
            </td>
            <td colspan="8">
              <div class="flex between">
                <div class="flex">
                  <div class="">
                    <span class="text-grey">订单号：</span
                    ><span class="text-blue">{{ item.order_no }}</span>
                  </div>
                  <div class="ml10">
                    <span class="text-grey">下单时间：</span
                    ><span>{{ item.create_time }}</span>
                  </div>
                  <div class="ml10">
                    <span class="text-grey">订单来源：</span
                    ><span>{{ item.order_source.name }}</span>
                  </div>

                  <template v-if="item.order_status.value == 4">
                    <el-tag
                      type="danger"
                      size="small"
                      class="ml10"
                      effect="light"
                    >
                      用户申请取消
                    </el-tag>
                  </template>

                  <template
                    v-if="
                      item.refund_status.value && item.refund_status.value != 5
                    "
                  >
                    <div class="ml10">
                      <span class="text-grey">售后：</span
                      ><span :class="`text-${item.refund_status.color}`">
                        {{ item.refund_status.name }}</span
                      >
                    </div>
                  </template>
                </div>

                <div class="flex end items-center">
                  <el-button
                    link
                    type="primary"
                    @click="_onRemark(item.id)"
                    v-permission="'store-order-update_remark'"
                    >备注</el-button
                  >
                  <el-button
                    link
                    type="primary"
                    @click="toDetail(item.id)"
                    v-permission="'store-order-detail'"
                    >详细</el-button
                  >
                </div>
              </div>
            </td>
          </tr>
          <template v-for="(goods, idx) in item.goods" :key="idx">
            <tr class="tr-line">
              <td v-if="idx == 0" :rowspan="item.goods.length"></td>
              <td>
                <div class="flex">
                  <el-avatar
                    shape="square"
                    :size="60"
                    :src="goods.goods_image"
                  ></el-avatar>
                  <div class="ml10">
                    <div class="order-goods-name te2">
                      {{ goods.goods_name }}
                    </div>
                    <div class="mt5">
                      <span class="text-grey">规格:</span>
                      <span>{{ goods.sku_attr_text }}</span>
                    </div>
                  </div>
                </div>
              </td>

              <td class="text-center">
                <money colorClass="text-grey" :value="goods.price"></money>
                <div class="text-grey">{{ goods.total_num }}件</div>
              </td>
              <template v-if="idx == 0">
                <td :rowspan="item.goods.length">
                  <div class="flex end">
                    <money :value="item.order_total_price"></money>
                  </div>
                  <template v-if="item.update_price.value != '0.00'">
                    <div class="flex end text-red">
                      <div>改：</div>
                      <div>{{ item.update_price.symbol }}</div>
                      <money :value="item.update_price.value"></money>
                    </div>
                  </template>
                  <div class="text-grey flex end mt5">
                    <div v-if="item.express_free">包邮</div>
                    <div v-else class="price">
                      <div>运费:</div>
                      <money :value="item.express_price"></money>
                    </div>
                  </div>
                </td>
                <td :rowspan="item.goods.length">
                  <userBox
                    :avatar="item.user_avatar"
                    :nickName="item.user_nickName"
                    :id="item.user_id"
                  ></userBox>
                </td>
                <td :rowspan="item.goods.length">
                  <template v-if="item.pay_status.value">
                    <pay-type :type="item.pay_type"></pay-type>
                  </template>
                  <template v-else>
                    <span class="text-grey">未付款</span>
                  </template>
                </td>

                <td class="text-center" :rowspan="item.goods.length">
                  <span class="tag dark default">{{
                    item.delivery_type.name
                  }}</span>
                </td>
                <td class="text-center" :rowspan="item.goods.length">
                  <template v-if="item.order_status.value == 2">
                    <div>
                      <span class="text-grey">付款：</span>
                      <span :class="`text-${item.pay_status.color}`">
                        {{ item.pay_status.name }}
                      </span>
                    </div>
                    <template v-if="item.delivery_type.value == 'express'">
                      <template v-if="item.pay_status.value">
                        <div class="mt5">
                          <span class="text-grey">发货：</span>
                          <span :class="`text-${item.delivery_status.color}`">
                            {{ item.delivery_status.name }}
                          </span>
                        </div>
                      </template>
                      <template v-if="item.delivery_status.value">
                        <div class="mt5">
                          <span class="text-grey">收货：</span>
                          <span :class="`text-${item.receipt_status.color}`">
                            {{ item.receipt_status.name }}
                          </span>
                        </div>
                      </template>
                    </template>
                    <template v-else>
                      <template v-if="item.pay_status.value">
                        <div class="mt5">
                          <span class="text-grey">取货：</span>
                          <span :class="`text-${item.delivery_status.color}`">
                            {{ item.delivery_status.name }}
                          </span>
                        </div>
                      </template>
                    </template>
                  </template>
                  <template v-else>
                    <span :class="`text-${item.order_status.color}`">
                      {{ item.order_status.name }}
                    </span>
                  </template>
                </td>
                <td :rowspan="item.goods.length">
                  <div
                    class="grid end text-right"
                    v-if="item.order_status.value"
                  >
                    <template v-if="item.order_status.value == 2">
                      <template v-if="!item.pay_status.value">
                        <!-- 未支付操作 -->
                        <div class="mt5">
                          <el-button
                            link
                            type="primary"
                            @click="_toUpdatePrice(item.id)"
                            v-permission="'store-order-update_price'"
                            >调整价格</el-button
                          >
                        </div>
                        <div class="mt5">
                          <el-button
                            link
                            type="primary"
                            @click="_toOfflinePayment(item.id)"
                            v-permission="'store-order-offline_payment'"
                            >线下支付</el-button
                          >
                        </div>
                        <div class="mt5">
                          <el-button
                            link
                            type="primary"
                            @click="_onCloseOrder(item.id)"
                            v-permission="'store-order-close'"
                            >关闭</el-button
                          >
                        </div>
                      </template>
                      <template
                        v-if="
                          item.pay_status.value && !item.delivery_status.value
                        "
                      >
                        <!-- 已支付 未发货/未取货 -->
                        <template v-if="item.delivery_type.value == 'express'">
                          <!-- 配送方式 快递 发货操作 -->
                          <div class="mt5">
                            <el-button
                              link
                              type="primary"
                              @click="_toOrderDelivery(item.id)"
                              v-permission="'store-order-delivery'"
                              >去发货</el-button
                            >
                          </div>
                          <div class="mt5">
                            <el-button
                              link
                              type="primary"
                              @click="_toUpdateAddress(item.id)"
                              v-permission="'store-order-update_address'"
                              >修改地址</el-button
                            >
                          </div>
                        </template>
                        <template v-else>
                          <!-- 配送方式 自提 核销 -->
                          <div class="mt5">
                            <el-button
                              link
                              type="primary"
                              @click="_onExtract(item.id)"
                              v-permission="'store-order-extract'"
                              >核销</el-button
                            >
                          </div>
                        </template>
                      </template>

                      <template
                        v-if="
                          item.delivery_status.value &&
                          !item.receipt_status.value
                        "
                      >
                        <!-- 已收货，是否进去确定取货 -->
                        <div class="mt5">
                          <el-button
                            link
                            type="primary"
                            @click="_onReceiptOrder(item.id)"
                            v-permission="'store-order-receipt'"
                            >确定收货</el-button
                          >
                        </div>
                      </template>
                    </template>
                    <template v-if="item.order_status.value == 4">
                      <!-- 订单取消审核 -->
                      <div class="mt5">
                        <el-button
                          link
                          type="primary"
                          @click="_toOrderCancel(item.id)"
                          v-permission="'store-order-cancel'"
                          >审核</el-button
                        >
                      </div>
                    </template>
                  </div>
                </td>
              </template>
            </tr>
          </template>
        </template>
      </tbody>
    </table>

    <!-- 分页 -->
    <div class="flex end">
      <page :listPage="listPage" @change="pageChange"></page>
    </div>
    <orderDetail ref="orderDetailRef"></orderDetail>
    <updatePrice ref="updatePriceRef" @success="toInit"></updatePrice>
    <offlinePayment ref="offlinePaymentRef" @success="toInit"></offlinePayment>
    <updateAddress ref="updateAddressRef" @success="toInit"></updateAddress>
    <orderDelivery ref="orderDeliveryRef" @success="toInit"></orderDelivery>
    <orderExtract ref="orderExtractRef" @success="toInit"></orderExtract>
    <orderCancel ref="orderCancelRef" @success="toInit"></orderCancel>
    <orderRemark ref="orderRemarkRef" @success="toInit"></orderRemark>
  </layout-body-tabs>
</template>
<script lang="ts" setup>
import { ref, getCurrentInstance, onMounted, watch, nextTick } from "vue";
import { getOrderList } from "@/api/store/order";
import { listPageType, enumType, Result, ResultError } from "@/types";
import { useConfig } from "@/store";
import userBox from "@/components/user/box.vue";
import orderDetail from "./detail.vue";
import updatePrice from "./update-price.vue";
import offlinePayment from "./offline-payment.vue";
import updateAddress from "./update-address.vue";
import orderDelivery from "./delivery.vue";
import orderExtract from "./extract.vue";
import orderCancel from "./cancel.vue";
import orderRemark from "./remark.vue";
import orderCommon from "./common";
import { value } from "dom7";
import type { FormInstance } from "element-plus";

const configStore = useConfig();

const { proxy } = getCurrentInstance() as any;

const {
  proxy: { $utils },
} = getCurrentInstance() as any;

const initLoading = ref<boolean>(true);

const lists = ref<any>([]);

const searchFormRef = ref<typeof FormInstance>();

const searchForm = ref<{
  search_key: string;
  search_value: string;
  soucre: string;
  pay_type: string;
  create_time: string;
}>({
  search_key: "order_no",
  search_value: "",
  soucre: "all",
  pay_type: "all",
  create_time: "",
});

const _searchValue = ref<string>("");

const searchValueChange = (val: string) => {
  searchForm.value.search_value = val;
};

const resetSearch = (formEl: typeof FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  _searchValue.value = "";
};

watch(
  () => searchForm.value,
  (val: any) => {
    initPage();
    toInit();
  },
  { deep: true }
);

const statusTabs = ref<enumType>([
  {
    name: "全部",
    value: "all",
  },
]);

const searchKeyData = ref<enumType>([
  {
    name: "订单号",
    value: "order_no",
  },
  {
    name: "交易流水号",
    value: "pay_transaction",
  },
]);

const orderSourceEnum = ref<enumType>([
  {
    name: "全部",
    value: "all",
  },
]);

const orderPayTypeEnum = ref<enumType>([
  {
    name: "全部",
    value: "all",
  },
]);

const orderStatus = ref<string | number>("all");

const changeStatus = (val: string | number) => {
  orderStatus.value = val;
  initPage();
  toInit();
};

const listPage = ref<listPageType>({
  total: 0,
  limit: configStore.getPageLimit,
  page: 1,
});

const initPage = () => {
  lists.value = [];
  listPage.value.page = 1;
};

const toInit = () => {
  isCheckAll.value = false;
  indeterminate.value = false;
  selectedIds.value = [];
  let obj: any = {};
  obj.order_status = orderStatus.value;
  obj.page = listPage.value.page;
  obj.limit = listPage.value.limit;
  initLoading.value = true;
  getOrderList(Object.assign(obj, searchForm.value))
    .then((res: Result) => {
      lists.value = res.data.data;
      listPage.value.total = res.data.total;
      setTimeout(() => {
        initLoading.value = false;
      }, 500);
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const selectedIds = ref<Array<string | number>>([]);

const isCheckAll = ref<boolean>(false);

const indeterminate = ref<boolean>(false);

const selectedCheckbox = (id: number) => {
  if ($utils.inArray(id, selectedIds.value)) {
    var index = $utils.arrayFilterMultiple(selectedIds.value, false, id);
    selectedIds.value.splice(index, 1);
  } else {
    selectedIds.value.push(id);
  }
  initCheck();
};

const onCheckAll = () => {
  lists.value.forEach((item: any) => {
    if (!isCheckAll.value) {
      if (!$utils.inArray(item.id, selectedIds.value)) {
        selectedIds.value.push(item.id);
      }
    } else if ($utils.inArray(item.id, selectedIds.value)) {
      var index = $utils.arrayFilterMultiple(selectedIds.value, false, item.id);
      selectedIds.value.splice(index, 1);
    }
  });
  initCheck();
};

const initCheck = () => {
  if (
    selectedIds.value.length > 0 &&
    selectedIds.value.length < lists.value.length
  ) {
    indeterminate.value = true;
    isCheckAll.value = false;
  } else if (selectedIds.value.length > 0) {
    indeterminate.value = false;
    isCheckAll.value = true;
  } else {
    indeterminate.value = false;
    isCheckAll.value = false;
  }
};

const {
  _onCloseOrder,
  _toOrderDelivery,
  _toUpdateAddress,
  _toOfflinePayment,
  _toUpdatePrice,
  _onExtract,
  _toOrderCancel,
  _onRemark,
  _onReceiptOrder,
} = orderCommon(toInit);

const pageChange = (res: listPageType) => {
  listPage.value = res;
  toInit();
};

const orderDetailRef = ref<HTMLElement>();

const toDetail = (id: number) => {
  proxy?.$refs["orderDetailRef"].open(id);
};

const updatePriceRef = ref<HTMLElement>();

const offlinePaymentRef = ref<HTMLElement>();

const updateAddressRef = ref<HTMLElement>();

const orderDeliveryRef = ref<HTMLElement>();

const orderExtractRef = ref<HTMLElement>();

const orderCancelRef = ref<HTMLElement>();

const orderRemarkRef = ref<HTMLElement>();

onMounted(() => {
  nextTick(() => {
    let sourceEnumObj = configStore.getEnumItem("store.order.SourceEnum"),
      statusEnumObj = configStore.getEnumItem("store.order.StatusEnum"),
      payTypeEnumObj = configStore.getEnumItem("pay.PayTypeEnum");
    for (let k in sourceEnumObj) {
      orderSourceEnum.value.push(sourceEnumObj[k]);
    }
    for (let k in statusEnumObj) {
      statusTabs.value.push(statusEnumObj[k]);
    }
    console.log(statusTabs.value);
    for (let k in payTypeEnumObj) {
      orderPayTypeEnum.value.push(payTypeEnumObj[k]);
    }
    toInit();
  });
});
</script>

<style scoped>
.order-table {
  width: 100%;
  min-height: 200px;
  border-collapse: collapse;
}
.order-table thead tr {
  background-color: #f3f3f3;
}
.order-table td,
.order-table td,
.order-table th {
  padding: 12px 15px;
  font-size: 12px;
  color: #333333;
  font-weight: 500;
}
.order-table th {
  border: 0;
  border-right: none;
  box-sizing: border-box;
  text-overflow: ellipsis;
  vertical-align: middle;
  position: relative;
  line-height: 23px;
  padding: 12px 15px;
}
.order-table .tr-line td {
}
.order-table .tr-line td {
  border: 1px solid #ebeef5;
}
.order-table .header-row {
}

.order-goods-name {
  max-width: 240px;
}
.order-table-check {
  width: 18px;
  height: 18px;
  border: 1px solid #dcdcdc;
  cursor: pointer;
  margin: 0 5px 0 0;
  position: relative;
  display: inline-block;
  background: #fff;
  appearance: none;
  box-sizing: border-box;
  border-radius: 0;
  vertical-align: bottom;
  -webkit-appearance: none;
  padding: 0;
  border-radius: 2px;
}
.order-table-check:checked:after,
.order-table-check.indeterminate:after {
  color: #fff;
  background: var(--base-default);
  height: 16px;
  line-height: 16px;
  width: 16px;
  text-align: center;
  border: 1px solid var(--base-default);
  top: -1px;
  left: -1px;
  display: block;
  font-style: normal;
  position: absolute;
  font-family: icon;
  border-radius: 2px;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
.order-table-check.indeterminate:after {
  content: "\e725";
  font-size: 12px;
}

.order-table-check:checked:after {
  content: "\e73d";
  font-size: 16px;
}
</style>